<template>
  <div :class="computedClasses">
    <h2 v-if="followedCitiesWithTemp.length === 0">
      暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。
    </h2>
    <div v-else class="followed-cities-list">
      <div
        class="city"
        v-for="(item, index) in followedCitiesWithTemp"
        :key="index"
        @mouseenter="showAction = index"
        @mouseleave="showAction = null"
      >
        <div class="left">
          <h3>{{ item.city }}</h3>
          <span>{{ item.temperature }}度</span>
        </div>
        <div class="right" v-if="showAction === index">
          <button @click="lookUpCity(item)">查看</button>
          <button @click="deleteCity(item.adcode)">删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

import { useWeatherStore } from '@/stores/weather'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'

const router = useRouter()
const { followedCitiesWithTemp, searchUlShow, selectedCity } = storeToRefs(useWeatherStore())
const { deleteCity } = useWeatherStore()

const showAction = ref(null) // 用于跟踪显示的城市索引

const computedClasses = computed(() => {
  if (searchUlShow.value) {
    if (followedCitiesWithTemp.value.length === 0) {
      return 'followed-cities mt80'
    } else {
      return 'followed-cities hidden'
    }
  } else {
    return 'followed-cities'
  }
})

const lookUpCity = (item) => {
  selectedCity.value = item.city
  const path = `/${item.adcode}?search=${item.city}`
  router.push(path)
}
</script>

<style lang="scss" scoped>
.followed-cities {
  h2 {
    color: white;
    font-size: 16px;
    font-weight: 400;
    line-height: 24px;
    text-align: center;
  }

  .followed-cities-list {
    margin-top: 40px;
    // 设定最大高度，超出部分显示滚动条
    max-height: 300px;
    overflow-y: auto;
    scrollbar-width: thin;

    .city {
      display: flex;
      justify-content: space-between;

      .left {
        display: flex;
        justify-content: space-between;
        width: 100%;
        margin-bottom: 16px;
        padding: 8px 16px;
        background-color: rgb(0, 78, 113);
        cursor: pointer;
        transition: all 0.3s;

        span,
        h3 {
          color: white;
          font-size: 16px;
          font-weight: 400;
          line-height: 24px;
        }
      }

      &:hover .left {
        width: 80%;
      }

      .right {
        display: flex;
        gap: 8px;
        margin-bottom: 16px;

        button {
          width: 80px;
          background-color: rgb(234, 179, 8);
          color: white;
          font-size: 16px;
          line-height: 24px;
          text-align: center;
          border: none;
          cursor: pointer;
        }
      }
    }
  }
}
.followed-cities.mt80 {
  margin-top: 80px;
}

.followed-cities.hidden {
  display: none;
}
</style>
